package com.scau.classOnline.service;

import com.scau.classOnline.dao.SignatureMapper;
import com.scau.classOnline.dao.UserMapper;
import com.scau.classOnline.dto.UserDTO;
import com.scau.classOnline.entity.Signature;
import com.scau.classOnline.entity.User;
import com.scau.classOnline.model.UserDetailModel;
import com.scau.classOnline.utils.time.TimeFormatUtil;
import com.scau.classOnline.utils.time.TimePattern;
import com.tls.tls_sigature.tls_sigature;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

@SuppressWarnings("SpringJavaInjectionPointsAutowiringInspection")
@Service
@Transactional
public class UserService implements UserDetailsService {

    @Autowired
    private UserMapper userMapper;
    @Autowired
    private SignatureMapper signatureMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        User user = userMapper.selectByUsername(username);
        if (user == null) {
            throw new UsernameNotFoundException("用户名不对!");
        }
        return user;
    }

    public int register(User user) {
//        if (loadUserByUsername(user.getName()) != null) { //换成此种写法报错，不知为什么
        if (userMapper.selectByUsername(user.getUsername()) != null) {
            return -1;
        }
        BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
        user.setPassword(encoder.encode(user.getPassword()));
        if (userMapper.insert(user.getUsername(), user.getPassword(), user.getEmail(), user.getStatus()) == 1) {
            user = userMapper.selectByUsername(user.getUsername());
            return createSig(user.getId());
        }
        return 0;
    }

    public User findByEmail(String email) {
        User user = null;
        try {
            user = userMapper.selectByEmail(email);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return user;
    }

    public boolean motifyPassword(Integer userId, String newPassword) {
        BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
        if (userMapper.updatePasswordByUserId(userId, encoder.encode(newPassword)) > 0) {
            return true;
        }
        return false;
    }

    public int addRolesForUser(String username) {
        User user = userMapper.selectByUsername(username);
        List<Integer> roles = new ArrayList<>();
        roles.add(user.getStatus());

        return userMapper.insertRolesForUser(user.getId(), (Integer[]) roles.toArray(new Integer[roles.size()]));
    }

    public User findByUsername(String username) {
        return userMapper.selectByUsername(username);
    }

    public User findByUserId(Integer id) {
        return userMapper.selectByPrimaryKey(id);
    }

    public UserDetailModel getUserDetailModelById(Integer id) {
        User user = userMapper.selectByPrimaryKey(id);
        UserDetailModel userDetailModel = new UserDetailModel();
        BeanUtils.copyProperties(user, userDetailModel);
        userDetailModel.setCreateTime(TimeFormatUtil.convertDateToString(user.getCreateTime(), TimePattern.SECOND));
        return userDetailModel;
    }

    @Transactional
    public boolean modifyUserModelById(UserDTO userDTO) {
        User user = new User();
        BeanUtils.copyProperties(userDTO, user);
        int result = userMapper.updateUserInfoByPrimaryKey(user);
//         todo exception
        if (result <= 0) {
            return false;
        }
        return true;
    }

    public int createSig(Integer uid) {
        String priKeyContent = "-----BEGIN PRIVATE KEY-----\n" +
                "MIGHAgEAMBMGByqGSM49AgEGCCqGSM49AwEHBG0wawIBAQQgeYskEcz9+IXeHN18\n" +
                "+i22AXm0hywK2U8nNgYKfTfJGLuhRANCAAR8h2pYdnvqfDoi4HeEen6PSp2Oy56q\n" +
                "VavOf6uoPeYhxpQWPd19pwv5/aGeI1MvmYH5QTe0seVLDvSo/hu0ebHU\n" +
                "-----END PRIVATE KEY-----\n";
        String identifier = uid.toString();
        tls_sigature.GenTLSSignatureResult result = tls_sigature.genSig(1400234803, identifier, priKeyContent);
        String mySig = result.urlSig;
        String head = mySig.substring(0, mySig.length() / 2 + 1);
        String tail = mySig.substring(mySig.length() / 2 + 1);
        Signature sig = new Signature(uid, head, tail);
        return signatureMapper.insert(sig);
    }

    public Signature getSig(Integer uid) {
        return signatureMapper.selectByPrimaryKey(uid);
    }
}
